package com.jerry.controller;

import com.jerry.BO.UserDetail;
import com.jerry.response.CommonResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.Objects;
import java.util.UUID;
@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {
    public final MongoTemplate mongoTemplate;
    //public final StringRedisTemplate redisTemplate;

    public UserController(MongoTemplate mongoTemplate) {
        this.mongoTemplate = mongoTemplate;
    }

    @PostMapping("/login")
    public CommonResponse login(@RequestParam("username")String username ,
                                @RequestParam("password")String password){
        UserDetail userDetail = mongoTemplate.findById(username, UserDetail.class);
        if (Objects.isNull(userDetail))
            return CommonResponse.error();
        if (!userDetail.getPassWord().equals(password))
            return CommonResponse.error();
        String token = UUID.randomUUID().toString();
        //redisTemplate.opsForValue().set(token,username);
        return CommonResponse.success(token);
    }

    @PostMapping("/regist")
    public CommonResponse regist(@RequestParam("username")String username ,
                                @RequestParam("password")String password){
        log.info("进入注册");
        UserDetail userDetail = new UserDetail().setUserName(username)
                .setPassWord(password);
        mongoTemplate.insert(userDetail);
        return CommonResponse.success();
    }
}
